<template>
    <div class="file-list">
        <div class="file-item" v-for="file in fileList" :key="file">
            <el-image :src="getIcon(file)" @click="download(file)"
                :preview-src-list="getType(file) == 'image' ? [file] : false" :zoom-rate="1.2"></el-image>
        </div>
        <div v-if="!fileList.length">无</div>
    </div>
</template>

<script setup>
import word from "@/assets/images/mall/word.png";
import pdf from "@/assets/images/mall/pdf.png";
import video from "@/assets/images/mall/video.png";
import excel from "@/assets/images/mall/excel.png";

defineProps({
    fileList: {
        type: Array[String],
        default: () => []
    }
})

const fileTypes = {
    image: ['jpg', 'png', 'jpeg', 'gif'],
    video: ['mp4', 'avi'],
    excel: ['xls', 'xlsx'],
    word: ['doc', 'docx'],
    pdf: ['pdf'],
}
const icons = { word, pdf, excel, video };
/**
 * 获取文件类型
 */
const getType = (url) => {
    let type = ''
    for (let key in fileTypes) {
        fileTypes[key].filter(v => {
            if (url.indexOf(v) != -1) {
                type = key;
            }
        })
    }
    return type;
}
/**
 * 根据类型返回相应图标
 */
const getIcon = (url) => {
    let icon = '';
    if (getType(url) == 'image') icon = url;
    else icon = icons[getType(url)];
    return icon;
}
/**
 * 下载文件
 */
const download = (url) => {
    if (getType(url) == 'image') return;
    const link = document.createElement('a');
    link.href = url;
    link.download = getType(url);
    link.target = "_blank"; // 可选，如果希望在新窗口中下载文件，请取消注释此行
    link.click();
}
</script>

<style scoped>
.file-list {
    display: flex;
}
</style>